<template>
  <div>
    <!-- 表单 -->
    <Form :model="monthForm" style="display: block;">
      <Row gutter="40">
        <i-col span="6">
          <FormItem>
            <Cascader change-on-select :data="organizationList" v-model="monthForm.organization" @on-change="organizationChange" placeholder="所属机构" clearable></Cascader>
          </FormItem>
        </i-col>
        <i-col span="6">
          <FormItem>
            <Select v-model="monthForm.empolyee" placeholder="员工" :clearable="isClearable">
              <Option
                v-for="item in empolyeeList"
                :key="item.key"
                :value="item.key"
              >{{item.value}}-{{item.key}}</Option>
            </Select>
          </FormItem>
        </i-col>
        <i-col span="6">
          <FormItem>
            <Select v-model="monthForm.attendMonth" placeholder="考勤月份" clearable>
              <Option v-for="item in attendMonthList" :key="item" :value="item">{{item}}</Option>
            </Select>
          </FormItem>
        </i-col>
        <i-col span="6">
          <FormItem>
            <Select v-model="monthForm.role" placeholder="所属角色" :clearable="isClearable">
              <Option v-for="item in roleList" :key="item.key" :value="item.key">{{item.value}}</Option>
            </Select>
          </FormItem>
        </i-col>
      </Row>
      <Row gutter="40">
        <i-col span="6">
          <FormItem>
            <Select v-model="monthForm.attendStatus" placeholder="考勤状态" clearable>
              <Option
                v-for="item in attendStatusList"
                :key="item.value"
                :value="item.value"
              >{{item.label}}</Option>
            </Select>
          </FormItem>
        </i-col>
      </Row>
      <Row>
        <FormItem>
          <Button type="primary" style="margin-right:20px" @click="handleSubmit(1)">查询</Button>
          <Button @click="handleReset()" :disabled="resetButtonDisabled">重置</Button>
        </FormItem>
      </Row>
    </Form>
    <!-- 查询数据 -->
    <Table :columns="monthColumns" :data="monthData">
      <template slot-scope="{row}" slot="lateHour">
        <span v-if="row.lateTime == 0">{{row.lateTime}}</span>
        <span
          v-else
          style="color:red;cursor:pointer"
          @click="offWork=true;currentRow = row;monthDetail(row,'1')"
        >{{row.lateTime}}</span>
      </template>

      <template slot-scope="{row}" slot="earlyTime">
        <span v-if="row.earlyTime == 0">{{row.earlyTime}}</span>
        <span
          v-else
          style="color:red;cursor:pointer"
          @click="offWork=true;currentRow = row;monthDetail(row,'2')"
        >{{row.earlyTime}}</span>
      </template>

      <template slot-scope="{row}" slot="attendanceRate">
        <span>{{row.dutyDays!=='0'?(row.beDutyDays/row.dutyDays).toFixed(4)*100:0}}%</span>
      </template>
    </Table>
    <!-- 分页 -->
    <Page
      :total="total"
      show-sizer
      show-total
      style="text-align:right;margin-top:20px"
      @on-change="pageChange"
      @on-page-size-change="pageSizeChange"
      :page-size-opts="pageSizeOptions"
      :current="pageIndex"
      :page-size="pageSize"
      transfer
    ></Page>
    <Modal
      footer-hide="true"
      :value="offWork"
      :mask-closable="false"
      @on-visible-change="modalVisibleChange"
      width="800"
    >
      <span slot="header" style="color:#fff;font-size:16px">{{currentRow.month}}&nbsp;&nbsp;迟到时长汇总</span>
      <div class="modalContent">
        <div class="image"><img :src="headPortrait"/></div>
        <div class="baseContent">
          <div class="name">{{currentRow.uname}}</div>
          <div class="otherContent">
            所属机构：{{currentRow.organization}}
            <span style="margin-left:5px;margin-right:5px;">|</span>
            角色：{{currentRow.urole}}
          </div>
        </div>
      </div>
      <span style="display:block;clear:both"></span>

      <Table :columns="lateColumns" :data="lateData">
        <template slot-scope="{row}" slot="attendResult">
          <span style="color:red">{{row.detail}}</span>
        </template>
      </Table>

      <!-- 对话框分页 -->
      <Page
        :total="total2"
        show-sizer
        show-total
        style="text-align:right;margin-top:20px;margin-bottom:30px;"
        @on-change="pageChange2"
        @on-page-size-change="pageSizeChange2"
        :page-size-opts="pageSizeOptions2"
      ></Page>
    </Modal>
  </div>
</template>

<script>
import {exportFile} from "../../../util/util"
export default {
  props: {
    monthPass: {
      type: String
    }
  },
  data() {
    return {
      monthForm: {
        organization: [],
        empolyee: "",
        attendMonth: "",
        role: "",
        attendStatus: ""
      },
      organizationList: [],
      empolyeeList: [],
      attendMonthList: [],
      roleList: [],
      attendStatusList: [
        {
          value: "0",
          label: "异常"
        },
        {
          value: "1",
          label: "正常"
        }
      ],
      monthColumns: [
        {
          title: "月度",
          key: "month",
          fixed: "left",
          width: "120"
        },
        {
          title: "姓名",
          key: "uname",
          fixed: "left",
          width: "150"
        },
        {
          title: "工号",
          key: "uno",
          align: "center",
          width: "130"
        },
        {
          title: "所属机构",
          key: "organization",
          width: "250"
        },
        {
          title: "角色",
          key: "urole",
          width: "120"
        },
        {
          title: "应出勤天数",
          key: "dutyDays",
          width: "120"
        },
        {
          title: "实际出勤天数",
          key: "beDutyDays",
          width: "120"
        },
        {
          title: "请假天数",
          key: "leaveDay",
          width: "100"
        },
        {
          title: "迟到次数",
          key: "lateTimes",
          width: "100"
        },
        {
          title: "迟到时长",
          key: "lateTime",
          slot: "lateHour",
          width: "100"
        },
        {
          title: "早退次数",
          key: "earlyTimes",
          width: "100"
        },
        {
          title: "早退时长",
          key: "earlyTime",
          width: "100",
          slot: "earlyTime"
        },
        {
          title: "地点异常天数",
          key: "wrongPlaceDay",
          width: "100"
        },
        {
          title: "旷工天数",
          key: "offDays",
          width: "100"
        },
        {
          title: "出勤率",
          key: "attendanceRate",
          slot: "attendanceRate",
          minWidth: 100
        }
      ],
      monthData: [],
      currentRow: "",
      offWork: false,
      lateColumns: [
        {
          title: "日期",
          key: "date",
          width: "150"
        },
        {
          title: "员工打卡时间",
          key: "time",
          align: "center",
          width: "250"
        },
        {
          title: "考勤结果",
          key: "detail",
          slot: "attendResult",
          width: "400"
        }
      ],
      lateData: [],
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      total2: 0,
      pageIndex2: 1,
      pageSize2: 10,
      pageSizeOptions2: [5, 10, 15, 20],
      pageSizeOptions: [5, 10, 15, 20],
      cou: "",
      isClearable: true,
      resetButtonDisabled: false,
      headPortrait:'',
    };
  },
  methods: {
    // 对话框关闭设置
    modalVisibleChange(bool) {
      if (bool == false) {
        this.offWork = false;
      }
    },

    // 重置
    handleReset() {
      this.monthForm = {
        organization: [],
        empolyee: "",
        attendMonth: "",
        role: "",
        attendStatus: ""
      };
    },

    // 提交
    handleSubmit() {
      this.pageIndex = 1;
      this.pageSize = 10;
      if (
        !this.monthForm.organization &&
        !this.monthForm.empolyee &&
        !this.monthForm.attendMonth &&
        !this.monthForm.role &&
        !this.monthForm.attendStatus
      ) {
        this.$Message.error("请至少选择一个条件");
        return;
      }
      let obj = {
        organization: this.monthForm.organization[this.monthForm.organization.length-1],
        uNo: this.monthForm.empolyee,
        month: this.monthForm.attendMonth,
        uRole: this.monthForm.role,
        attendanceRate: this.monthForm.attendStatus,
        index: this.pageIndex,
        pageSize: this.pageSize
      };
      this.pageObj = obj;
      this.api.uerAttendanceMonth(obj).then(res => {
        if (res.code == 200 && res.data != null) {
          this.$emit("modifyMonthFlag", false);
          this.monthData = res.data.records;
          this.monthData.forEach(element => {
            if (element.month) {
              element.month =
                element.month.substr(0, 4) +
                "年" +
                element.month.substr(5, 4) +
                "月";
            }
          });
          this.$Message.info(res.msg);
          this.total = res.data.total;
        } else {
          this.$emit("modifyMonthFlag", true);
          this.monthData = [];
          this.total = 0;
          this.$Message.info(res.msg);
        }
      });
    },

    // 分页查询
    pageSubmit() {
      this.pageObj.index = this.pageIndex;
      this.pageObj.pageSize = this.pageSize;
      this.api.uerAttendanceMonth(this.pageObj).then(res => {
        if (res.code == 200 && res.data.total > 0) {
          this.monthData = res.data.records;
          this.monthData.forEach(element => {
            if (element.month) {
              element.month =
                element.month.substr(0, 4) +
                "年" +
                element.month.substr(5, 4) +
                "月";
            }
          });
          this.total = res.data.total;
        } else {
          this.monthData = [];
          this.total = 0;
          this.$Message.error(res.msg);
        }
      });
    },

    // 分页设置
    pageChange(pageIndex) {
      this.pageIndex = pageIndex;
      this.pageSubmit();
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageSubmit();
    },

    // 对话框分页设置
    pageChange2(pageIndex) {
      this.pageIndex2 = pageIndex;
      this.monthDetail(this.currentRow, this.cou);
    },
    pageSizeChange2(pageSize) {
      this.pageSize2 = pageSize;
      this.monthDetail(this.currentRow, this.cou);
    },

    // 对话框详情
    monthDetail(row, cou) {
      this.headPortrait = ''
      let obj1 = {  
        no: row.uno
      }
      this.api.getUserChatHeadByNo(obj1).then(res => {
        if (res.code == 200 && res.data != null) {
          this.headPortrait = res.data;
        }
      });
      this.cou = cou;
      row.month = row.month.substr(0, 4) + "-" + row.month.substr(5, 2);
      let obj = {
        id: row.id,
        month: row.month,
        status: cou,
        index: this.pageIndex2,
        pageSize: this.pageSize2,
        uNo: row.uno
      };
      this.api.uerAttendanceMonthDetail(obj).then(res => {
        if (res.code == 200 && res.data.total > 0) {
          this.total2 = res.data.total;
          this.lateData = res.data.records;
          this.lateData.forEach(record => {
            if (record.signTime) {
              record.date = record.signTime.substr(0, 10);
              record.time = record.signTime.substr(10, 6);
            }
          });
        }
      });
    },

    exportExcel() {
      if (
        !this.monthForm.organization &&
        !this.monthForm.empolyee &&
        !this.monthForm.attendMonth &&
        !this.monthForm.role &&
        !this.monthForm.attendStatus
      ) {
        this.$Message.error("请至少选择一个条件");
        return;
      }
      let obj = {
        organization: this.monthForm.organization[this.monthForm.organization.length-1],
        uNo: this.monthForm.empolyee,
        month: this.monthForm.attendMonth,
        uRole: this.monthForm.role,
        attendanceRate: this.monthForm.attendStatus
      };
      exportFile("scrm-gateway/scrm-uer/api/export/uerAttendanceMonthExcel",obj)
      // let url = "../rest/export/uerAttendanceMonthExcel";
      // window.open(
      //   url +
      //     "?organization=" +
      //     obj.organization +
      //     "&uNo=" +
      //     obj.uNo +
      //     "&month=" +
      //     obj.month +
      //     "&uRole=" +
      //     obj.uRole +
      //     "&attendanceRate=" +
      //     obj.attendanceRate
      // );
    },

    // 获取当前机构及以下
    getOrganizationList() {
      this.api.remanagecomList().then(res => {
        if (res.code == 200 && res.data != null) {
          let arr = []
          arr.push(res.data)
          arr.forEach(one=>{
            one.value = one.comcode
            one.label = one.comcode + '-' + one.name
            one.children = one.chilDren || []
            if (one.children) {
              one.chilDren.forEach(two=>{
                two.value = two.comcode
                two.label = two.comcode + '-' + two.name
                two.children = two.chilDren || []
                if (two.children) {
                  two.children.forEach(three=>{
                    three.value = three.comcode
                    three.label = three.comcode + '-' + three.name
                    three.children = three.chilDren || []
                    if (three.children) {
                      three.children.forEach(four=>{
                        four.value = four.comcode
                        four.label = four.comcode + '-' + four.name
                        four.children = four.chilDren || []
                      })
                    }
                  })
                }
              })
            }
          })
          console.log(arr);
          this.organizationList = arr
        } else {
          this.organizationList = [];
        }
      });
      this.api.organizationDict().then(res => {
        if (res.code == 200 && res.data != null) {
          let a = JSON.stringify(res.data[0].map);
          if (a !== "{}") {
            let b = a.substr(1, a.length - 2);
            let c = b.split(",");
            c.forEach(element => {
              let d = element.split(":");
              this.roleList.push({
                key: d[0].replace(/\"/g, ""),
                value: d[1].replace(/\"/g, "")
              });
            });
          }
          // if (res.data[0].listKeyValueVOS.length > 0) {
          //   this.organizationList = res.data[0].listKeyValueVOS;
          // }
          // 角色是外勤的处理
          if (this.roleList.length == 1 && this.roleList[0].key == 1) {
            this.isClearable = false;
            this.resetButtonDisabled = true;
            this.monthForm.organization = this.organizationList[0].value;
            this.organizationChange([this.monthForm.organization]);
            this.monthForm.role = this.roleList[0].key;
          }
        } else {
          this.$Message.error(res.msg);
        }
      });

      this.api.getAkkMonthly().then(res => {
        if (res.code == 200) {
          this.attendMonthList = res.data;
        }
      });
    },

    // 机构改变，查询员工
    organizationChange(value) {
      if (value) {
        this.monthForm.empolyee = "";
        if (value) {
          let obj = {
            managecom: value
          };
          $.ajax("scrm-gateway/scrm-uer/api/uerList/selectuser/" + value[value.length-1], {
            method: "get",
            contentType: "application/json;charset=utf-8",
            beforeSend: function(xhr) {
              xhr.setRequestHeader(
                "Authorization",
                sessionStorage.getItem("credentials")
              );
            },
            success: res => {
              if (res.data.length > 0) {
                this.empolyeeList = res.data;
                if (this.roleList.length == 1 && this.roleList[0].key == 1) {
                  this.monthForm.empolyee = this.empolyeeList[0].key;
                }
              } else {
                this.empolyeeList = [];
              }
            },
            error: res => {
              this.$Message.error(res.msg);
            }
          });
        }
      } else {
        this.empolyeeList = [];
        this.monthForm.empolyee = "";
      }
    }
  },
  mounted() {
    // 获取当前机构及以下
    this.getOrganizationList();
  },
  watch: {
    monthPass: function(val, oldVal) {
      this.exportExcel();
    }
  },
  beforeDestroy() {
    this.monthForm = null;
    this.organizationList = null;
    this.empolyeeList = null;
    this.attendMonthList = null;
    this.roleListv
    this.attendStatusList = null;
    this.monthColumns = null;
    this.monthData = null;
    this.currentRow = null;
    this.offWork = null;
    this.lateColumns = null;
    this.lateData = null;
    this.total = null;
    this.pageIndex = null;
    this.pageSize = null;
    this.total2 = null;
    this.pageIndex2 = null;
    this.pageSize2 = null;
    this.pageSizeOptions2 = null;
    this.pageSizeOptions = null;
    this.cou = null;
    this.isClearable = null;
    this.resetButtonDisabled = null;
    this.headPortrait = null;
  }
};
</script>

<style lang="less" scoped>
@import "./dayCount.less";
</style>

<style>
.ivu-modal-header {
  background-color: #2d8cf0;
}
.ivu-modal-close .ivu-icon-ios-close {
  color: #fff !important;
}
</style>